/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/maximum-binary-tree
   @Language: C++
   @Datetime: 19-05-14 15:24
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	TreeNode *preorder(vector<int> &nums, int begin, int end){
		if(begin==end) return NULL;
		int val=INT_MIN, id=-1;
		for(int i=begin; i<end; ++i){
			if(nums[i]>val){
				val=nums[i];
				id=i;
			}
		}
		TreeNode *root=new TreeNode(val);
		root->left=preorder(nums,begin,id);
		root->right=preorder(nums,id+1,end);
		return root;
	}
public:
	/**
	 * @param nums: an array
	 * @return: the maximum tree
	 */
	TreeNode * constructMaximumBinaryTree(vector<int> &nums) {
		// Write your code here
		return preorder(nums,0,nums.size());
	}
};
